﻿using DotNetMVC.Common;
using DotNetMVC.DTO;
using DotNetMVC.IService;
using DotNetMVC.Website.Areas.WebAdmin.Common;
using DotNetMVC.Website.Areas.WebAdmin.Filters;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace DotNetMVC.Website.Areas.WebAdmin.Controllers
{
    [AdminAuthorize(IsCheck = true)]
    public class SiteContentController : Controller
    {
        public ISiteContentService siteContentService { get; set; }
        public ISiteNavService siteNavService { get; set; }

        // GET: WebAdmin/SiteContent

        #region 介绍页
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">菜单Id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult InfoEdit(long id)
        {
            SiteContentDTO model = siteContentService.GetInfoDTOByNavId(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到介绍页信息");
            }
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult InfoEdit(long id, string cont)
        {
            SiteContentDTO dto = siteContentService.GetDTOById(id);
            if (dto == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到介绍页内容信息" });
            }

            siteContentService.UpdateInfo(id, cont);

            //生成介绍页静态页
            StaticPageHelper.Info(ControllerContext, id);
            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改介绍页：" + dto.Title + "（Id:" + id + "）");

            return Json(new AjaxResult { Status = "ok" });
        }
        #endregion

        #region 新闻资讯
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">菜单Id</param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult NewsList(long id, int pageIndex = 1)
        {
            long total;
            int pageSize = 10, maxPagerCount = 10;
            SiteContentDTO[] list = siteContentService.GetDTOPagedData(id, out total, pageIndex, pageSize);
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;

            //菜单Id
            ViewBag.NavId = id;
            return View(list);
        }

        [HttpGet]
        public ActionResult NewsAdd(long id)
        {
            //菜单Id
            ViewBag.NavId = id;
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewsAdd(long id, string title, string submitDate, string cont, string imgLG, int sort)
        {
            SiteNavDTO dtoNav = siteNavService.GetDTOById(id);
            if (dtoNav == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到菜单信息" });
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "标题不能为空" });
            }
            if (string.IsNullOrEmpty(submitDate))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期不能为空" });
            }
            DateTime date;
            if (!DateTime.TryParse(submitDate, out date))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期格式出错" });
            }
            if (string.IsNullOrEmpty(cont))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "内容不能为空" });
            }

            long newId = siteContentService.AddNews(id, title, date, cont, imgLG, sort).Id;
            //生成详细页静态页
            StaticPageHelper.News(ControllerContext, newId);
            //生成列表页静态页
            StaticPageHelper.NewsList(ControllerContext, id);
            //生成列表页静态页
            StaticPageHelper.NewsList(ControllerContext, id);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "新增新闻资讯：" + title + "（Id:" + newId + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        public ActionResult NewsEdit(long id)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到新闻资讯信息");
            }
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewsEdit(long id, string title, string submitDate, string cont, string imgLG, int sort)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到新闻资讯信息" });
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "标题不能为空" });
            }
            if (string.IsNullOrEmpty(submitDate))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期不能为空" });
            }
            DateTime date;
            if (!DateTime.TryParse(submitDate, out date))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期格式出错" });
            }
            if (string.IsNullOrEmpty(cont))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "内容不能为空" });
            }
            siteContentService.UpdateNews(id, title, date, cont, imgLG, sort);
            //生成详细页静态页
            StaticPageHelper.News(ControllerContext, id);
            //生成列表页静态页
            StaticPageHelper.NewsList(ControllerContext, model.SiteNavId);
            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            #region 测试
            /*
               Stopwatch watchUpdateNews = new Stopwatch();
               watchUpdateNews.Start();
               siteContentService.UpdateNews(id, title, date, cont, imgLG, sort);
               watchUpdateNews.Stop();
               int watchUpdateNewsElapsed = watchUpdateNews.Elapsed.Milliseconds;

               Stopwatch watchNews = new Stopwatch();
               watchNews.Start();
               //生成详细页静态页
               StaticPageHelper.News(ControllerContext, id);
               watchNews.Stop();
               int watchNewsElapsed = watchNews.Elapsed.Milliseconds;

               Stopwatch watchNewsList = new Stopwatch();
               watchNewsList.Start();
               //生成列表页静态页
               StaticPageHelper.NewsList(ControllerContext, model.SiteNavId);
               watchNewsList.Stop();
               int watchNewsListElapsed = watchNewsList.Elapsed.Milliseconds;

               Stopwatch watchHome = new Stopwatch();
               watchHome.Start();
               //生成首页静态页
               StaticPageHelper.Home(ControllerContext);
               watchNewsList.Stop();
               int watchHomeElapsed = watchHome.Elapsed.Milliseconds;
               */
            #endregion


            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改新闻资讯：" + title + "（Id:" + id + "）");

            /*
            return Json(new AjaxResult { Status = "ok", Data = new {
                UpdateNews="UpdateNews 耗时：" + watchUpdateNewsElapsed + "毫秒",
                News = "News 耗时：" + watchNewsElapsed + "毫秒",
                NewsList = "NewsList 耗时：" + watchNewsListElapsed + "毫秒",
                Home = "Home 耗时：" + watchHomeElapsed + "毫秒"
            } });
            */
            return Json(new AjaxResult { Status = "ok", });
        }

        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult NewsToHtml(long id)
        //{
        //    StaticPageHelper.RebuildNews(ControllerContext, id);
        //    return Json(new AjaxResult { Status = "ok" });
        //}
        #endregion

        #region 资料下载
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">菜单Id</param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DownloadList(long id, int pageIndex = 1)
        {
            long total;
            int pageSize = 10, maxPagerCount = 10;
            SiteContentDTO[] list = siteContentService.GetDTOPagedData(id, out total, pageIndex, pageSize);
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;

            //菜单Id
            ViewBag.NavId = id;
            return View(list);
        }

        [HttpGet]
        public ActionResult DownloadAdd(long id)
        {
            //菜单Id
            ViewBag.NavId = id;
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult DownloadAdd(long id, string title, string submitDate, string downloadFile, string imgLG, int sort)
        {
            SiteNavDTO dtoNav = siteNavService.GetDTOById(id);
            if (dtoNav == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到菜单信息" });
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "标题不能为空" });
            }
            if (string.IsNullOrEmpty(submitDate))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期不能为空" });
            }
            DateTime date;
            if (!DateTime.TryParse(submitDate, out date))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期格式出错" });
            }
            if (string.IsNullOrEmpty(downloadFile))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "请上传资料文件" });
            }

            long newId = siteContentService.AddDownload(id, title, date, downloadFile, imgLG, sort).Id;

            //生成列表页静态页
            StaticPageHelper.DownloadList(ControllerContext, id);
            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "新增资料下载：" + title + "（Id:" + newId + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        public ActionResult DownloadEdit(long id)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到资料下载信息");
            }
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult DownloadEdit(long id, string title, string submitDate, string downloadFile, string imgLG, int sort)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到资料下载信息" });
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "标题不能为空" });
            }
            if (string.IsNullOrEmpty(submitDate))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期不能为空" });
            }
            DateTime date;
            if (!DateTime.TryParse(submitDate, out date))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "发布日期格式出错" });
            }
            if (string.IsNullOrEmpty(downloadFile))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "请上传资料文件" });
            }

            siteContentService.UpdateDownload(id, title, date, downloadFile, imgLG, sort);

            //生成列表页静态页
            StaticPageHelper.DownloadList(ControllerContext, model.SiteNavId);
            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改资料下载：" + title + "（Id:" + id + "）");

            return Json(new AjaxResult { Status = "ok" });

        }
        #endregion

        #region 友情链接
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">菜单Id</param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult LinkList(long id, int pageIndex = 1)
        {
            long total;
            int pageSize = 10, maxPagerCount = 10;
            SiteContentDTO[] list = siteContentService.GetDTOPagedData(id, out total, pageIndex, pageSize);
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;

            //菜单Id
            ViewBag.NavId = id;
            return View(list);
        }

        [HttpGet]
        public ActionResult LinkAdd(long id)
        {
            //菜单Id
            ViewBag.NavId = id;

            #region 打开方式
            List<SelectListItem> listTarget = new List<SelectListItem>();
            listTarget.Add(new SelectListItem { Value = "_self", Text = "原窗口打开" });
            listTarget.Add(new SelectListItem { Value = "_blank", Text = "弹出新窗口" });
            ViewBag.ListTarget = listTarget;
            #endregion

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult LinkAdd(long id, string title, string linksUrl, string listLinksTarget, string imgLG, int sort)
        {
            SiteNavDTO dtoNav = siteNavService.GetDTOById(id);
            if (dtoNav == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到菜单信息" });
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "链接名称不能为空" });
            }

            if (string.IsNullOrEmpty(linksUrl))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "链接地址不能为空" });
            }

            long newId = siteContentService.AddLink(id, title, linksUrl, listLinksTarget, imgLG, sort).Id;


            //生成列表页静态页
            StaticPageHelper.LinkList(ControllerContext, id);
            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "新增友情链接：" + title + "（Id:" + newId + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        public ActionResult LinkEdit(long id)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到友情链接信息");
            }

            #region 打开方式
            List<SelectListItem> listTarget = new List<SelectListItem>();
            listTarget.Add(new SelectListItem { Value = "_self", Text = "原窗口打开" });
            listTarget.Add(new SelectListItem { Value = "_blank", Text = "弹出新窗口" });
            ViewBag.ListTarget = listTarget;
            #endregion

            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult LinkEdit(long id, string title, string linksUrl, string listLinksTarget, string imgLG, int sort)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到友情链接信息" });
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "链接名称不能为空" });
            }

            if (string.IsNullOrEmpty(linksUrl))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "链接地址不能为空" });
            }

            siteContentService.UpdateLink(id, title, linksUrl, listLinksTarget, imgLG, sort);

            //生成列表页静态页
            StaticPageHelper.LinkList(ControllerContext, model.SiteNavId);
            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改友情链接：" + title + "（Id:" + id + "）");

            return Json(new AjaxResult { Status = "ok" });

        }
        #endregion

        #region 图片展示
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">菜单Id</param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ImageList(long id, int pageIndex = 1)
        {
            long total;
            int pageSize = 10, maxPagerCount = 10;
            SiteContentDTO[] list = siteContentService.GetDTOPagedData(id, out total, pageIndex, pageSize);
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;

            //菜单Id
            ViewBag.NavId = id;
            return View(list);
        }

        [HttpGet]
        public ActionResult ImageAdd(long id)
        {
            //菜单Id
            ViewBag.NavId = id;
            #region 打开方式
            List<SelectListItem> listTarget = new List<SelectListItem>();
            listTarget.Add(new SelectListItem { Value = "_self", Text = "原窗口打开" });
            listTarget.Add(new SelectListItem { Value = "_blank", Text = "弹出新窗口" });
            ViewBag.ListTarget = listTarget;
            #endregion
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ImageAdd(long id, string title, string linksUrl, string listLinksTarget, string imgLG, int sort)
        {
            SiteNavDTO dtoNav = siteNavService.GetDTOById(id);
            if (dtoNav == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到菜单信息" });
            }

            if (string.IsNullOrEmpty(imgLG))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "请上传图片" });
            }

            long newId = siteContentService.AddImage(id, title, linksUrl, listLinksTarget, imgLG, sort).Id;

            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "新增图片展示：" + title + "（Id:" + newId + "）");

            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        public ActionResult ImageEdit(long id)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到图片展示信息");
            }
            #region 打开方式
            List<SelectListItem> listTarget = new List<SelectListItem>();
            listTarget.Add(new SelectListItem { Value = "_self", Text = "原窗口打开" });
            listTarget.Add(new SelectListItem { Value = "_blank", Text = "弹出新窗口" });
            ViewBag.ListTarget = listTarget;
            #endregion
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ImageEdit(long id, string title, string linksUrl, string listLinksTarget, string imgLG, int sort)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到图片展示信息" });
            }

            if (string.IsNullOrEmpty(imgLG))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "请上传图片" });
            }

            siteContentService.UpdateImage(id, title, linksUrl, listLinksTarget, imgLG, sort);

            //生成首页静态页
            StaticPageHelper.Home(ControllerContext);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改图片展示：" + title + "（Id:" + id + "）");

            return Json(new AjaxResult { Status = "ok" });

        }
        #endregion

        #region 删除
        [HttpPost]
        public ActionResult Delete(long id)
        {
            SiteContentDTO model = siteContentService.GetDTOById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到" + model.NavName + "信息" });
            }
            siteContentService.MarkDeleted(id);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "删除" + model.NavName + ":" + model.Title + "（Id:" + model.Id + "）");
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        public ActionResult BatchDelete(long[] selectdIds)
        {
            if (selectdIds.Length <= 0)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "未选中删除数据" });
            }

            List<long> list = new List<long>();
            foreach (long id in selectdIds)
            {
                list.Add(id);
            }
            siteContentService.BatchMarkDeleted(list);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "批量删除内容（Ids:" + string.Join(",", list) + "）");

            return Json(new AjaxResult { Status = "ok" });
        }
        #endregion
    }
}